<?php
class MailControl extends Control
{
    protected $mailer;
    protected $content;
    protected $textTemplate;
    protected $path;

    public function MailControl()
    {
        parent::__construct();
        $this->mailer = new PhpMailer(true);
    }

    public function SetSubject($subject)
    {
        $this->mailer->Subject = $subject;
    }

    public function SetPriority($priority)
    {
        $this->mailer->Priority = $priority;
    }

    public function SetFrom($address, $name  = null)
    {
        $this->mailer->SetFrom($address, $name);
    }

    public function AddReplyTo($address, $name  = null)
    {
        $this->mailer->AddReplyTo($address, $name);
    }

    public function AddTo($address, $name = null)
    {
        $this->mailer->AddAddress($address, $name);
    }

    public function AddCc($address, $name  = null)
    {
        $this->mailer->AddCC($address, $name);
    }

    public function AddBcc($address, $name  = null)
    {
        $this->mailer->AddBCC($address, $name);
    }

    public function AddAttachment($file)
    {
        $this->mailer->AddAttachment($file);
    }

    public function AddContent($content)
    {
        $this->content = $content;
    }

    public function Render()
    {
        return $this->content ? $this->content : parent::Render();
    }

    public function RenderPlainText()
    {
        if ($this->textTemplate)
            return $this->textTemplate->Render();
    }

    public function Replace($key, $value = null)
    {
        parent::Replace($key, $value);
        if ($this->textTemplate)
            $this->textTemplate->Replace($key, $value);
    }

    public function Repeat($zone, $data, $callback = null)
    {
        parent::Repeat($zone, $data, $callback);
        if ($this->textTemplate)
            $this->textTemplate->Repeat($zone, $data, $callback);
    }

    public function SetTemplate($file = null)
    {
        if (!$file) return;

        parent::SetTemplate($file);
        $text_path = $this->path.DS.'plain_text'.DS.$this->templateFile.'.txt';
        if (file_exists($text_path))
            $this->textTemplate = new Template($text_path);
    }

    public function Send()
    {
        $this->mailer->Body = $this->Render();
        $this->mailer->AltBody = $this->RenderPlainText();
        $this->mailer->Send();
    }
}
?>
